package com.yimi.yinhepda.views.unload_module.palletbind;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.RecycleAdapter.ForkliftAdapter;
import com.pda.ym.base.CommonViewHolder;
import com.pda.ym.base.BaseTitleActivity;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.ForklifStatisticsTableDao;
import com.yimi.yinhepda.db.table.ForkliftStatisticsTable;
import com.yimi.yinhepda.entity.bean.StatForkliftTaskDetail;
import com.yimi.yinhepda.entity.bean.StatForkliftTaskDetailIndex;
import com.yimi.yinhepda.entity.request.ForkliftUnBindRequest;
import com.yimi.yinhepda.entity.response.ForkListResponse;
import com.yimi.yinhepda.entity.response.QueryPlateUnBundDictResponse;
import com.yimi.yinhepda.entity.response.SuccessResponse;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.yimi.yinhepda.utils.ListUtils;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.utils.UcWaybillValidate;

import org.jetbrains.annotations.NotNull;

import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 叉车分拣解绑界面
 *
 * @author xionggaosheng
 */
public class ForkliftUnBindActivity extends BaseTitleActivity implements CommonViewHolder.onItemCommonClickListener {
    /**
     * 列表
     */
    private RecyclerView listView;
    /**
     * 适配器
     */
    private ForkliftAdapter adapter;
    /**
     * 列表数据集合
     */
    List<StatForkliftTaskDetail> dataList = new ArrayList<>();
    /**
     * 子单数据集合
     */
    List<StatForkliftTaskDetailIndex> childDataList = new ArrayList<>();
    /**
     * 返回
     */
    private ImageButton ibBack;
    /**
     * 离线绑定按钮
     */
    private Button btnOffline;
    /**
     * 提交按钮
     */
    private Button btnCommit;
    /**
     * 叉车分货统计表操作
     */
    private ForklifStatisticsTableDao forklifStatisticsTableDao;
    /**
     * 托盘数
     */
    private TextView tvPalletNum;
    /**
     * 货区数
     */
    private TextView tvAreaCodeNum;
    /**
     * 票数
     */
    private TextView tvPiaoNum;
    /**
     * 计费重量
     */
    private TextView tvChargedNum;
    /**
     * 叉车分货统计数据
     */
    private List<ForkliftStatisticsTable> tableList;
    /**
     * 是否需要逐票解绑
     */
    private boolean mNeedPallet;

    public ForkliftUnBindActivity() {
        super(true);
    }

    @Override
    public String getPageName() {
        return "叉车分货";
    }

    @Override
    public int setContentViewId() {
        return R.layout.activity_fork_lift;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listView = findViewById(R.id.rv_task_no);
        ibBack = findViewById(R.id.ib_back);
        btnOffline = findViewById(R.id.btn_offline);
        btnCommit = findViewById(R.id.btn_commit);
        tvPalletNum = findViewById(R.id.tv_palletNum);
        tvAreaCodeNum = findViewById(R.id.tv_areaCodeNum);
        tvChargedNum = findViewById(R.id.tv_chargedWeight);
        tvPiaoNum = findViewById(R.id.tv_piao_num);

        ibBack.setOnClickListener(this);
        btnOffline.setOnClickListener(this);
        btnCommit.setOnClickListener(this);

        adapter = new ForkliftAdapter(this, dataList, this);
        listView.setLayoutManager(new LinearLayoutManager(this));
        listView.setAdapter(adapter);

        forklifStatisticsTableDao = new ForklifStatisticsTableDao();

        tableList = forklifStatisticsTableDao.findAll();

        if (tableList == null) {
            tableList = new ArrayList<>();
            tvPalletNum.setText("0");
            tvAreaCodeNum.setText("0");
            tvPiaoNum.setText("0");
            tvChargedNum.setText("0");
        } else {
            Map<String, String> palletNumMap = new HashMap<>();
            Map<String, String> areaCodeMap = new HashMap<>();
            Map<String, String> piaoNumMap = new HashMap<>();
            double chargeWeight = 0;
            for (ForkliftStatisticsTable entity : tableList) {
                palletNumMap.put(entity.getPalletNo(), entity.getPalletNo());
                areaCodeMap.put(entity.getPalletNo() + entity.getAreaCode(), entity.getAreaCode());
                piaoNumMap.put(entity.getWaybillNo(), entity.getWaybillNo());
                chargeWeight += entity.getChargedWeight();
            }
            tvPalletNum.setText(String.format("%s", palletNumMap.size()));
            tvAreaCodeNum.setText(String.format("%s", areaCodeMap.size()));
            tvPiaoNum.setText(String.format("%s", piaoNumMap.size()));
            DecimalFormat df = new java.text.DecimalFormat("#.##");
            tvChargedNum.setText(String.format("%s", df.format(chargeWeight)));

            //查询数据字典配合，判断该部门是逐票解绑还是全票解绑
            queryDictValue();
        }
    }

    /**
     * 查询数据字典配合，判断该部门是逐票解绑还是全票解绑
     */
    private void queryDictValue() {
        showPgDlg("正在查询配置...");
        Map<String, String> params = new HashMap<>();
        //托盘解绑数据字典字段
        params.put("params", "pallet_function");
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setUrl(Constants.URL_QUERY_DICT_VALUE)
                .setParams(params)
                .setConnTimeOut(5 * 1000)
                .setResponsClazz(QueryPlateUnBundDictResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryPlateUnBundDictResponse response = (QueryPlateUnBundDictResponse) obj;
                        if (response != null) {
                            if (response.getData() != null) {
                                Map<String, String> maps = response.getData().getPalletFunction();
                                if (maps != null) {
                                    for (String value : maps.values()) {
                                        //判断是否需要逐票解绑
                                        if (value.equals(sharedPreferUtil.getDeptCode())) {
                                            mNeedPallet = true;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
    }

    @Override
    protected void handleBarCode(final String result) {
        if (result == null) {
            showToast("运单扫描失败");
        } else if (!StringUtils.isWaybillNo(result) && !UcWaybillValidate.validate(result)) {
            showToast("单号不规范！(" + result + ")");
        } else {
            if (mNeedPallet) {
                //是逐票解绑
                if (childDataList.isEmpty()) {
                    //列表为空时拉托盘数据
                    showPgDlg("数据获取中...");
                    Map map = new HashMap();
                    map.put("childWayBillNo", result);
                    new NetRequest().setMethod(NetRequest.Method.GET)
                            .setUrl(Constants.URL_FIND_FORKLIFT)
                            .setParams(map)
                            .setResponsClazz(ForkListResponse.class)
                            .setConnTimeOut(10 * 1000)
                            .execute(new UICallBack() {
                                @Override
                                public void onError(String msg) {
                                    dismissPgDlg();
                                    SoundVibratorManager.playSound(2);
                                    showToast(msg);
                                }

                                @Override
                                public void onSuccess(Object obj) {
                                    dismissPgDlg();
                                    ForkListResponse response = (ForkListResponse) obj;
                                    if (response.getData() != null) {
                                        ForkListResponse.Task task = response.getData().getTask();
                                        if (task != null) {
                                            String date = DateHelper.formatTimeEightChinese(task.getOperTime());
                                            String empName = task.getScanEmp();
                                            String empCode = task.getScanEmpCode().split("@")[0];
                                            String msg = "该托盘已经于" + date + "被" + empName + "，工号为" + empCode + "分货提交过，请扫描其它托盘";
                                            MyDialog.showAlertDialog(ForkliftUnBindActivity.this, "系统提示", msg, "是");
                                            return;
                                        }
                                        List<StatForkliftTaskDetailIndex> detailIndices = response.getData().getDetail();
                                        if (detailIndices != null) {
                                            childDataList.addAll(detailIndices);
                                            dataList.clear();
                                            //按照产品类型排序
                                            dataList.addAll(sortList(getWaybillListData(childDataList)));
                                            adapter.notifyDataSetChanged();
                                        }
                                    }
                                    SoundVibratorManager.playSound(1);
                                }
                            });
                } else {
                    //托盘单号扫描
                    StatForkliftTaskDetailIndex requestBean = null;
                    for (StatForkliftTaskDetailIndex statForkliftTaskDetailIndex : childDataList) {
                        if (result.equals(statForkliftTaskDetailIndex.getChildWaybillNo())) {
                            requestBean = statForkliftTaskDetailIndex;
                        }
                    }

                    if (requestBean == null) {
                        showToast("该托盘不存在此单号(" + result + ")");
                        return;
                    }

                    showPgDlg("数据获取中...");
                    final StatForkliftTaskDetailIndex finalRequestBean = requestBean;
                    new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                            .setUrl(Constants.URL_FORK_UPDATE_SCAN_STATE)
                            .setRequestObject(requestBean)
                            .setResponsClazz(ForkListResponse.class)
                            .setConnTimeOut(10 * 1000)
                            .execute(new UICallBack() {
                                @Override
                                public void onError(String msg) {
                                    if (msg != null) {
                                        showToast(msg);
                                    } else {
                                        showToast("服务器出错了!");
                                    }
                                    SoundVibratorManager.playSound(2);
                                    dismissPgDlg();
                                }

                                @Override
                                public void onSuccess(Object obj) {
                                    showToast("扫描成功");
                                    for (StatForkliftTaskDetail statForkliftTaskDetail : dataList) {
                                        if (statForkliftTaskDetail.getAreaCode() == null || finalRequestBean.getAreaCode() == null) {
                                            if (result.startsWith(statForkliftTaskDetail.getWaybillNo())) {
                                                statForkliftTaskDetail.setCheck(true);
                                                continue;
                                            }
                                        } else if (statForkliftTaskDetail.getAreaCode().equals(finalRequestBean.getAreaCode())) {
                                            statForkliftTaskDetail.setCheck(true);
                                        }
                                    }
                                    adapter.notifyDataSetChanged();
                                    SoundVibratorManager.playSound(1);
                                    dismissPgDlg();
                                }
                            });
                }
            } else {
                //全票解绑
                if (childDataList.isEmpty()) {
                    //列表为空时拉托盘数据
                    showPgDlg("数据获取中...");
                    ForkliftUnBindRequest request = new ForkliftUnBindRequest();
                    request.setChildWayBillNo(result);
                    new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                            .setUrl(Constants.URL_FIND_FORKLIFT_AND_UNBIND)
                            .setRequestObject(request)
                            .setResponsClazz(ForkListResponse.class)
                            .setConnTimeOut(10 * 1000)
                            .execute(new UICallBack() {
                                @Override
                                public void onError(String msg) {
                                    dismissPgDlg();
                                    SoundVibratorManager.playSound(2);
                                    showToast(msg);
                                }

                                @Override
                                public void onSuccess(Object obj) {
                                    dismissPgDlg();
                                    ForkListResponse response = (ForkListResponse) obj;
                                    if (response.getData() != null) {
                                        ForkListResponse.Task task = response.getData().getTask();
                                        if (task != null) {
                                            String date = DateHelper.formatTimeEightChinese(task.getOperTime());
                                            String empName = task.getScanEmp();
                                            String empCode = task.getScanEmpCode().split("@")[0];
                                            String msg = "该托盘已经于" + date + "被" + empName + "，工号为" + empCode + "分货提交过，请扫描其它托盘";
                                            MyDialog.showAlertDialog(ForkliftUnBindActivity.this, "系统提示", msg, "是");
                                            return;
                                        }
                                        List<StatForkliftTaskDetailIndex> detailIndices = response.getData().getDetail();
                                        if (detailIndices != null) {
                                            childDataList.addAll(detailIndices);
                                            dataList.clear();
                                            //按照产品类型排序
                                            dataList.addAll(sortList(getWaybillListData(childDataList)));
                                            adapter.notifyDataSetChanged();
                                        }
                                    }
                                    SoundVibratorManager.playSound(1);
                                }
                            });
                } else {
                    showToast("已扫描，请先提交！");
                }
            }
        }
    }

    /**
     * 通过子单号集合拿到主单号（列表数据）集合
     */
    public List<StatForkliftTaskDetail> getWaybillListData(List<StatForkliftTaskDetailIndex> childWayBillList) {
        List<StatForkliftTaskDetail> data = new ArrayList<>();
        List<String> waybillList = new ArrayList<>();
        for (StatForkliftTaskDetailIndex statForkliftTaskDetailIndex : childWayBillList) {
            if (!waybillList.contains(statForkliftTaskDetailIndex.getWaybillNo())) {
                StatForkliftTaskDetail bean = new StatForkliftTaskDetail();
                bean.setNum(1);
                bean.setNextDept(statForkliftTaskDetailIndex.getNextDept());
                bean.setNextDeptCode(statForkliftTaskDetailIndex.getNextDeptCode());
                bean.setAreaCode(statForkliftTaskDetailIndex.getAreaCode());
                bean.setWaybillNo(statForkliftTaskDetailIndex.getWaybillNo());
                bean.setChargedWeight(statForkliftTaskDetailIndex.getChargedWeight());
                bean.setForkliftNo(statForkliftTaskDetailIndex.getForkliftNo());
                bean.setSrcPiecesNum(statForkliftTaskDetailIndex.getSrcPiecesNum());
                bean.setColumn9(statForkliftTaskDetailIndex.getColumn9());
                bean.setColumn10(statForkliftTaskDetailIndex.getColumn10());

                data.add(bean);
                waybillList.add(statForkliftTaskDetailIndex.getWaybillNo());
            } else {
                for (StatForkliftTaskDetail datum : data) {
                    if (datum.getWaybillNo().equals(statForkliftTaskDetailIndex.getWaybillNo())) {
                        datum.setNum(datum.getNum() + 1);
                    }
                }
            }
        }
        return data;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_back:
                finish();
                break;
            case R.id.btn_offline:
                if (dataList.size() > 0) {
                    showToast("请将当前数据叉车分货后再进入离线解绑");
                    return;
                }
                startActivity(new Intent(this, OffLineUnBindActivity.class));
                break;
            case R.id.btn_commit:
                if (childDataList.isEmpty()) {
                    showToast("无扫描任务，无法解绑");
                    return;
                }
                if (mNeedPallet) {
                    for (StatForkliftTaskDetail statForkliftTaskDetail : dataList) {
                        if (statForkliftTaskDetail.getAreaCode() == null ||
                                (statForkliftTaskDetail.getAreaCode() != null && StringUtils.isEmpty(statForkliftTaskDetail.getAreaCode()))) {
                            MyDialog dialog = new MyDialog(this);
                            dialog.setIcon(R.drawable.alert);
                            dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                            dialog.setTitle("提示");
                            dialog.setMessage("当前界面部分数据存在货区为空且不能正常完成分货，是否强制提交?");
                            dialog.setPositiveClickListener("是", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //解封数据
                                    commitUnbind();
                                    dialog.dismiss();
                                }
                            });
                            dialog.setNegativeClickListener(R.drawable.btn_login_selector, "否", null);
                            dialog.setCanceledOnTouchOutside(false);
                            dialog.show();
                            return;
                        }
                    }

                    for (StatForkliftTaskDetail statForkliftTaskDetail : dataList) {
                        if (!statForkliftTaskDetail.isCheck()) {
                            MyDialog dialog = new MyDialog(this);
                            dialog.setIcon(R.drawable.alert);
                            dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                            dialog.setTitle("提示");
                            dialog.setMessage("当前提交的数据存在未分完货区的情况，是否强制提交！");
                            dialog.setPositiveClickListener("是", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //解封数据
                                    commitUnbind();
                                    dialog.dismiss();
                                }
                            });
                            dialog.setNegativeClickListener(R.drawable.btn_login_selector, "否", null);
                            dialog.setCanceledOnTouchOutside(false);
                            dialog.show();
                            return;
                        }
                    }
                    //提交托盘解绑数据
                    commitUnbind();
                } else {
                    MyDialog dialog = new MyDialog(this);
                    dialog.setIcon(R.drawable.alert);
                    dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                    dialog.setTitle("提示");
                    dialog.setMessage("确定提交解绑？");
                    dialog.setPositiveClickListener("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            commitUnbind();
                        }
                    });
                    dialog.setNegativeClickListener(R.drawable.btn_login_selector, "取消", null);
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.show();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClickListener(int position) {

    }

    @Override
    public void onItemLongClickListener(int position) {

    }

    /**
     * 解绑提交
     */
    private void commitUnbind() {
        if (childDataList.isEmpty()) {
            showToast("无扫描任务，无法解绑");
            return;
        }

        showPgDlg("数据提交中...");
        Map map = new HashMap();
        map.put("forkliftNo", childDataList.get(0).getForkliftNo());
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setUrl(Constants.URL_FORK_UPDATE_FORKLIFT_TASK)
                .setParams(map)
                .setResponsClazz(SuccessResponse.class)
                .setConnTimeOut(10 * 1000)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        if (msg != null) {
                            showToast(msg);
                        } else {
                            showToast("服务器出错了!");
                        }
                        SoundVibratorManager.playSound(2);
                        dismissPgDlg();
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        submitHandler();
                    }
                });
    }

    /**
     * 提交处理，保存数据，清空界面数据
     */
    private void submitHandler() {
        //工号
        String workNo = sharedPreferUtil.getWorkNum();
        //部门编码
        String deptCode = sharedPreferUtil.getDeptCode();
        //计费重量
        double chargedWeight = 0;
        //托盘号
        Map<String, String> palletNumMap = new HashMap<>();
        //货区
        Map<String, String> areaCodeMap = new HashMap<>();
        //票数
        Map<String, String> piaoNumMap = new HashMap<>();

        if (tableList != null) {
            //遍历统计的表数据
            for (ForkliftStatisticsTable entity : tableList) {
                palletNumMap.put(entity.getPalletNo(), entity.getPalletNo());
                areaCodeMap.put(entity.getPalletNo() + entity.getAreaCode(), entity.getAreaCode());
                piaoNumMap.put(entity.getWaybillNo(), entity.getWaybillNo());
                chargedWeight += entity.getChargedWeight();
            }
        }

        //遍历列表数据
        for (StatForkliftTaskDetail statForkliftTaskDetail : dataList) {

            chargedWeight += (statForkliftTaskDetail.getChargedWeight() / statForkliftTaskDetail.getSrcPiecesNum()) * statForkliftTaskDetail.getNum();
            double tempWeight = (statForkliftTaskDetail.getChargedWeight() / statForkliftTaskDetail.getSrcPiecesNum()) * statForkliftTaskDetail.getNum();
            palletNumMap.put(statForkliftTaskDetail.getForkliftNo(), statForkliftTaskDetail.getForkliftNo());
            areaCodeMap.put(statForkliftTaskDetail.getForkliftNo() + statForkliftTaskDetail.getAreaCode(), statForkliftTaskDetail.getAreaCode());
            piaoNumMap.put(statForkliftTaskDetail.getWaybillNo(), statForkliftTaskDetail.getWaybillNo());

            ForkliftStatisticsTable statisticsTable =
                    new ForkliftStatisticsTable(workNo, deptCode, statForkliftTaskDetail.getForkliftNo(), statForkliftTaskDetail.getWaybillNo(),
                            statForkliftTaskDetail.getAreaCode(), statForkliftTaskDetail.getNextDeptCode(), statForkliftTaskDetail.getNextDept(),
                            statForkliftTaskDetail.getNum(), tempWeight);
            try {
                //叉车分货数据插入数据库
                forklifStatisticsTableDao.insert(statisticsTable);
            } catch (SQLException e) {
                e.printStackTrace();
            }

            tableList.add(statisticsTable);
        }

        //更新界面数据
        tvPalletNum.setText(String.format("%s", palletNumMap.size()));
        tvAreaCodeNum.setText(String.format("%s", areaCodeMap.size()));
        tvPiaoNum.setText(String.format("%s", piaoNumMap.size()));
        DecimalFormat df = new java.text.DecimalFormat("#.##");
        if (Double.isNaN(chargedWeight)) {
            chargedWeight = 0;
        }
        tvChargedNum.setText(String.format("%s", df.format(chargedWeight)));
        showToast("任务解绑成功");
        childDataList.clear();
        dataList.clear();
        adapter.notifyDataSetChanged();
        SoundVibratorManager.playSound(1);
    }

    /**
     * 数据排序
     * 二级排序 时>比>优>串>标
     */
    private List<StatForkliftTaskDetail> sortList(List<StatForkliftTaskDetail> list) {
        for (StatForkliftTaskDetail item : list) {
            //设置二级排序
            item.setSecondSort(Common.setSecondType(item.getColumn10(), item.getColumn9(), item.getWaybillNo()));
        }
        String[] sortNameArr = {"secondSort"};
        // true升序,false降序
        boolean[] isAscArr = {true};
        ListUtils.sort(list, sortNameArr, isAscArr);
        return list;
    }

    @Override
    public boolean showBack() {
        return true;
    }

    @Override
    public void setBack() {
        finish();
    }

    @NotNull
    @Override
    public String setTitle() {
        return getPageName();
    }

}
